<template>
    <el-upload class="upload-demo" drag :action="uploadImageAction" multiple
    :headers="{token}" name="img[]"  :data="{image_class_id:imageClassId}" 
    :on-success="uploadSuccess" :on-error="uploadError" :on-remove="removeImage">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
            Drop file here or <em>click to upload</em>
        </div>
        <template #tip>
            <div class="el-upload__tip">
                jpg/png files with a size less than 500kb
            </div>
        </template>
    </el-upload>
</template>
<script setup>
import {uploadImageAction, deleteImage} from '../api/image'
import { getToken } from '../composables/auth'
import {ref} from 'vue'
import { toast } from '../composables/util';
defineProps({
    imageClassId: {
        type: Number,
        default: 0
    }
})

const getUploadFiles = () => {
    return uploadFiles.value
}

defineExpose({getUploadFiles})



const emit = defineEmits(["upload-change"])

const token = getToken()

const uploadFiles = ref(null)
const uploadSuccess = (response, uploadFile, uploadFiles) => {
    uploadFiles.value = uploadFiles
    emit("upload-change", uploadFiles.value)
}

const uploadError = (error, uploadFile, uploadFiles) => {
    toast("图片上传失败：" + (JSON.parse(error.message).msg || "系统错误"),"error")
    uploadFiles.value = uploadFiles
    emit("upload-change", uploadFiles.value)
}

const removeImage = (uploadFile, uploadFiles) => {
    deleteImage([uploadFile.response.data.id||0]).finally(()=>{
        uploadFiles.value = uploadFiles
        emit("upload-change", uploadFiles.value)
    })
}
</script>
